package com.stand.hardcode.controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.stand.hardcode.entity.Item;
import com.stand.hardcode.entity.StandUser;
import com.stand.hardcode.database.PMF;

@SuppressWarnings("serial")
public class GenerateDummyObjectsServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		com.google.appengine.api.datastore.Query mydeleteq = new com.google.appengine.api.datastore.Query();
		PreparedQuery pq = datastore.prepare(mydeleteq);
		for (Entity result : pq.asIterable()) {
		    datastore.delete(result.getKey());      
		}   
		
		//Clear all old data
		Query q = pm.newQuery(StandUser.class);
		List<StandUser> userResults = (List<StandUser>) q.execute();
		for (StandUser u : userResults) {
			pm.deletePersistent(u);
		}
		
		q = pm.newQuery(Item.class);
		List<Item> itemResults = (List<Item>) q.execute();
		for (Item i : itemResults) {
			pm.deletePersistent(i);
		}
		
		//Make 25 items
		for (int i=0; i<25; i++) {
			Calendar expiry = GregorianCalendar.getInstance();
			expiry.add(Calendar.DATE, i);
			
			Item item = new Item();
			//item.setKey(key);
			item.setCreationTime(GregorianCalendar.getInstance().getTime());
			item.setDescription("Description " + i);
			item.setExpiryDate(expiry.getTime());
			//item.setItemPermissions(itemPermissions);
			item.setPhotoURL("No photo");
			item.setPrice(i);
			item.setQuantity(i);
			//item.setStatus(status);
			item.setTitle("Item "+ i);
			pm.makePersistent(item);
		}
		
		
		//Make 5 users
		for (int i=0; i<5; i++) {
			StandUser user = new StandUser("user" + i, "user" + i + "@gmail.com");
			pm.makePersistent(user);
		}
		
		pm.close();
		
		try {
			response.getOutputStream().print("Dummy items and users generated");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
